package cn.aylog.controller;

import cn.aylog.pojo.Employee;
import cn.aylog.service.IEmployee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class EmployeeController {

    @Autowired
    private IEmployee service;

    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public ModelAndView listAll(ModelAndView mv) {
        List<Employee> list = service.list();
        mv.addObject("employees", list);
        mv.setViewName("list");
        return mv;
    }

    @RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
    public String deleteById(@PathVariable Integer id) {
        service.delete(id);
        return "redirect:/listAll";
    }

    @RequestMapping(value = "/toAdd", method = RequestMethod.GET)
    public String toAdd() {
        return "add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(Employee emp) {
        service.add(emp);
        return "redirect:/listAll";
    }

    @RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
    public ModelAndView toUpdate(ModelAndView mv, @PathVariable Integer id) {
        Employee emp = service.list(id);
        mv.addObject("employee", emp);
        mv.setViewName("update");
        return mv;
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public String update(Employee emp) {
        service.update(emp);
        return "redirect:/listAll";
    }

    @RequestMapping("/text")
    @ResponseBody
    public String text() {
        return "{name: 'tom'}";
    }

}
